﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;


namespace Onetube.Providers
{
   public class YoutubeinMp3Provider
    {
       public  YoutubeinMp3Provider()
       {

       }

       public async Task<Entities.YoutubeinMp3> GetUrlAsync(string videoId, CancellationTokenSource cancelToken)
       {
           try
           {
               StringBuilder petitionUri = new StringBuilder("http://youtubeinmp3.com/fetch/?");

               string uri = string.Format("http://www.youtube.com/watch?v={0}", videoId);
               petitionUri.AppendFormat("api={0}", "advanced");
               petitionUri.AppendFormat("&format={0}", "JSON");
               petitionUri.AppendFormat("&video={0}", uri);

               var taskCompletitionSource = new TaskCompletionSource<Entities.YoutubeinMp3>();

               return await ResolveRequest(petitionUri, taskCompletitionSource, cancelToken).ConfigureAwait(false);
           }
           catch (Exception ex)
           {

               return null;
           }
          
       }

       private async Task<Entities.YoutubeinMp3> ResolveRequest(StringBuilder petitionUri, TaskCompletionSource<Entities.YoutubeinMp3> taskCompletitionSource, CancellationTokenSource cancelToken)
       {
           if (cancelToken == null)
           {
               cancelToken = new CancellationTokenSource();
           }

           using (HttpClient client = new HttpClient())
           {

               HttpResponseMessage response = await client.GetAsync(petitionUri.ToString(), cancelToken.Token).ConfigureAwait(false);

               string resultJson;
               using (StreamReader reader = new StreamReader(await response.Content.ReadAsStreamAsync().ConfigureAwait(false), Encoding.UTF8))
               {
                   try
                   {
                       resultJson = await reader.ReadToEndAsync().ConfigureAwait(false);

                       if (!string.IsNullOrEmpty(resultJson))
                       {

                           //resultJson = resultJson.Substring(resultJson.IndexOf("[") + 1);
                           //resultJson = resultJson.Substring(0, resultJson.LastIndexOf("]"));
                           var entries = JsonConvert.DeserializeObject<Entities.YoutubeinMp3>(resultJson, new JsonSerializerSettings { Formatting= Formatting.None });

                           taskCompletitionSource.SetResult(entries);
                           resultJson = null;
                           entries = null;
                       }
                       else
                       {
                           taskCompletitionSource.SetResult(null);
                       }
                       response.Dispose();
                   }
                   catch (Exception ex)
                   {
                       taskCompletitionSource.SetException(ex);
                   }
               }
           }
           return await taskCompletitionSource.Task;
       }
    }
}
